// middleware/visit-tracker.global.js
import _ from 'lodash'

let lastTrackedPath = ''
let sessionStartTime = Date.now()

const isDynamicRoute = (path) => path.match(/\/\[.+\]/)
const isInternalPath = (path) => path.startsWith('/_nuxt') || path.startsWith('/_ipx')
const isSameRoute = (to, from) => to.path === from.path
const isSessionNew = () => Date.now() - sessionStartTime > 1000 * 30 // 30秒新会话

const trackVisit = _.debounce(async (to, from) => {
  const userStore = useUserStore()
  const { $fetchAuth, $fetchGov } = useNuxtApp()

  // 生成访问标识
  const si = useCookie('si', {
    default: () => Math.floor(Math.random() * Number.MAX_SAFE_INTEGER),
    maxAge: 60 * 60 * 24 * 365
  }).value

  let uv = localStorage.getItem('uv')
  if (!uv) {
    uv = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER)
    localStorage.setItem('uv', uv)
  }

  try {
    const fetchMethod = userStore.token?.accessToken ? $fetchAuth : $fetchGov
    await fetchMethod('/app/api/visit', {
      method: 'POST',
      body: {
        si,
        uv,
        url:location.href,
        path:to.path,
        is_new_session: isSessionNew() ? 1 : 0,
        route_depth: to.matched.length
      },
      retry: 0
    })
    
    // 重置会话时间
    if (isSessionNew()) {
      sessionStartTime = Date.now()
    }
  } catch (error) {
    console.error('Visit tracking failed:', error)
  }
}, 500, { leading: true, trailing: false })

export default defineNuxtRouteMiddleware(async (to, from) => {
  if (!process.client) return
  if (isInternalPath(to.path)) return
  if (isDynamicRoute(to.matched[0]?.path)) return
  if (isSameRoute(to, from)) return
  if (to.path === lastTrackedPath) return

  lastTrackedPath = to.path
  trackVisit(to, from)
})